package com.wlj.validator;


import com.wlj.pojo.TbUser;
import com.wlj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

//自定义校验注解 的 校验逻辑
//不需要加注解@Component,因为实现了ConstraintValidator接口自动会注册为spring bean
public class UniqueConstraintValidator implements ConstraintValidator<UniqueConstraint,Object> {

    @Autowired
    private UserService userService;

    @Override
    public void initialize(UniqueConstraint uniqueConstraint) {
        System.out.println("my validator init");
    }

    //Object为校验的字段类型
    //返回true则校验成功
    //o为校验字段的值，constraintValidatorContext为校验注解里的属性值
    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        String username = (String) o;
        TbUser user = userService.findByUsername(username);
        return user==null?true:false;
    }
}
